<script setup lang="ts">
import { createRentAPI, delEnterpriseAPI, delRentAPI, getEnterpriseListAPI, getRentBuildListAPI, getRentListAPI, outRentAPI, uploadAPI } from '@/apis/enterprise';
import type { Datum, Enterprise, EnterpriseListParams } from '@/types/enterprise';
import { ElMessage, ElMessageBox, type FormRules, type UploadRawFile, type UploadRequestOptions } from 'element-plus';
import { ref } from 'vue';
import { useRouter } from 'vue-router';


// 1. 获取企业列表
const exterpriseList = ref<any[]> ([])
const params = ref<EnterpriseListParams> ({
  page: 1,
  pageSize: 5,
  name: ''
})

const total = ref(0)
const getExterpriseList = async () => {
  const res = await getEnterpriseListAPI(params.value)
  // exterpriseList.value = res.data?.rows
  exterpriseList.value  = []
  res.data.rows.forEach((item: Enterprise) => {
    exterpriseList.value.push({
      ...item,
      rentList: [] // 每一行补充存放合同的列表
    })
  })
  //  rentList: [] // 每一行补充存放合同的列表
  total.value = res.data?.total
}
getExterpriseList()

// 2. 分页
const pageChange = (page: number) => {
  // 更改参数
  params.value.page = page
  // 重新获取数据渲染
  getExterpriseList()
}

// 3. 搜索
const doSearch = ()=>{
  params.value.page = 1
  getExterpriseList()
}

// 4. 跳转到编辑页
const router = useRouter()
const editRent = (id: string) => {
  router.push({
    path: '/exterpriseAdd',
    query: {
      id
    }
  })
}

// 5 . 删除
const delExterprise = (id: string) => {
  ElMessageBox.confirm('确认删除该企业吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await delEnterpriseAPI(id)
    getExterpriseList()
    ElMessage({
      type: 'success',
      message: '删除成功!'
    })
  })
}

// 6. 添加合同
const rentForm = ref<any>({
  buildingId: undefined, // 楼宇id
  contractId: undefined, // 合同id
  contractUrl: '', // 合同Url
  enterpriseId: undefined, // 企业名称
  type: 0, // 合同类型
  rentTime: [] // 合同时间
})
const rentRules = ref<FormRules>({
  buildingId: [
    { required: true, message: '请选择楼宇', trigger: 'change' }
  ],
  rentTime: [
    { required: true, message: '请选择租赁日期', trigger: 'change' }
  ],
  contractId: [
    { required: true, message: '请上传合同文件' }
  ]
})

const rentDialogVisible = ref(false)
const addRent = (id: string)=>{
  rentDialogVisible.value = true
  // 获取楼宇数据
  getBuildList()
  // 记录企业的id
  rentForm.value.enterpriseId = id
}
const closeDialog = ()=>{
  rentDialogVisible.value = false
}

// 获取楼宇数据
const buildList = ref<{ id: string, name: string }[]>([])
const getBuildList = async ()=>{
  const res = await getRentBuildListAPI()
  buildList.value = res.data
}

const contractList = ref<any>([])
/**
 * 上传之前的校验
 * @param file 
 */
const beforeUpload = (file: UploadRawFile) => { 
  const allowImgType = ['application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/msword'].includes(file.type)
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!allowImgType) {
    ElMessage.error('上传合同文件只能是 .doc, .pdf 格式!')
  }
  if (!isLt5M) {
    ElMessage.error('上传合同文件大小不能超过 5MB!')
  }
  return allowImgType && isLt5M
}

const addForm = ref()
/**
 * 上传合同
 * @param fileData 
 */
const uploadHandle = async (fileData: UploadRequestOptions): Promise<any>=>{
  const { file } = fileData
  // 1. 包装formData对象
  const fd = new FormData()
  fd.append('file', file)
  fd.append('type', 'contract')
  const res = await uploadAPI(fd)
  
  // 2. 存储数据
  rentForm.value.contractId = res.data.id
  rentForm.value.contractUrl = res.data.url
  contractList.value.push(res.data)

  // 3. 单独校验表单
  addForm.value.validateField('contractId')
}

/**
 * 上传文件超出限制
 */
const onExceed = ()=>{
  ElMessage({
    message: '只能上传一份合同, 请先删除再重新上传',
    type: 'error'
  })
}

// 调用接口上传合同
const onCommitRent = ()=>{
  addForm.value.validate(async (valid: boolean) => {
    if (valid){
      const { buildingId, contractId, contractUrl, enterpriseId, type } = rentForm.value
      await createRentAPI({
        buildingId, contractId, contractUrl, enterpriseId, type,
        startTime: rentForm.value.rentTime[0],
        endTime: rentForm.value.rentTime[1]
      })
      ElMessage.success({ message: '添加合同成功' })
      // 更新列表
      await getExterpriseList()
      // 让所有的展开项都关闭
      expandRowKeys.value = []
      // 关闭弹框
      rentDialogVisible.value = false
      // 清除
      addForm.value.resetFields()
      rentForm.value.contractUrl = ''
      rentForm.value.contractId = ''
      contractList.value = []
    }
    
  })  
}


const expandRowKeys = ref<string[]>([])
/**
 * 展开或者关闭公司的二级选项
 */
const onExpandChange = async (row: any, expandedRows: any[])=>{
  // 1.1 判断点击时展开还是关闭
  const isExpend = expandedRows.find(item => item.id === row.id)
  // 1.2 判断
  if (isExpend){
    const res = await getRentListAPI(row.id)
    row.rentList = res.data
    // 把当前行公司的id放入expandRowKeys
    expandRowKeys.value.push(row.id)
  } else {
    // 关闭时，把当前行的合同列表清空
    row.rentList = []
    expandRowKeys.value = expandRowKeys.value.filter((id: string) => id !== row.id)
  }
}

const getStatusText = (status: number)=>{
  let statusText = ''
  switch(status){
    case 0:
      statusText =  '待生效';
      break;
    case 1:
      statusText = '生效中';
      break;
    case 2:
      statusText = '已到期';
      break;
    case 3:
      statusText = '已退租';
      break;
  }
  return statusText
}

// 格式化 tag 类型
const formatInfoType = (status: number) => {
  switch (status) {
    case 0:
      return 'warning';
    case 1:
      return 'success';
    case 2:
      return 'info';
    case 3:
      return 'danger';
  }
}


/**
 * 退租
 */
const outRent = async (row: any)=>{
  const res = await ElMessageBox.confirm('确认退租吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  if(res === 'confirm'){
    await outRentAPI(row.id)
    row.status = 3
  }
}

/**
 * 删除
 */
const delRent = async (row: any, exterpriseList: any)=>{
  const res = await ElMessageBox.confirm('确认删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  if (res === 'confirm') {
    await delRentAPI(row.id)
    // 找到当前合同在该公司所有合同中的下标
    const index = exterpriseList.rentList.findIndex((item: any) => item.id === row.id)
    // 根据下标去删除该合同
    exterpriseList.rentList.splice(index, 1)
  }
}
</script>

<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="params.name" clearable placeholder="请输入企业的名称" class="search-main" @clear="doSearch" />
      <el-button type="primary" @click="doSearch">查询</el-button>
    </div>
    <div class="create-container">
      <!-- <el-button v-auth-btn="`park:enterprise:add_edit`" type="primary"
        @click="$router.push('/exterpriseAdd')">添加企业</el-button> -->
      <auth-btn btnPerm="park:enterprise:add_edit">
        <el-button type="primary" @click="$router.push('/exterpriseAdd')">添加企业</el-button>
      </auth-btn>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="exterpriseList" @expand-change="onExpandChange" row-key="id"
        :expand-row-keys="expandRowKeys">
        <!-- 新增：展开部分 -->
        <el-table-column type="expand">
          <template #default="{row}">
            <el-table :data="row.rentList">
              <el-table-column align="center" label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column align="center" label="租赁起始时间" prop="startTime" />
              <el-table-column align="center" label="合同状态">
                <template #default="{row}">
                  <el-tag :type="formatInfoType(row.status)">{{ getStatusText(row.status) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="250">
                <!-- 获取插槽中传递出来的数据  -->
                <template #default="scope">
                  <el-button size="small" type="text">续租</el-button>
                  <el-button :disabled="scope.row.status === 3" size="small" type="text"
                    @click="outRent(scope.row)">退租</el-button>
                  <!-- 
                   scope.row: 合同对象
                   row: 公司对象 
                   -->
                  <el-button :disabled="!(scope.row.status === 3)" size="small" type="text"
                    @click="delRent(scope.row, row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column align="center" type="index" label="序号" width="120" />
        <el-table-column align="center" label="企业名称" width="320" prop="name" />
        <el-table-column align="center" label="联系人" prop="contact" />
        <el-table-column align="center" label="联系电话">
          <template #default="scope">
            <span>{{ scope.row.contactNumber.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="320">
          <template #default="scope">
            <el-button size="small" type="text" @click="addRent(scope.row.id)">添加合同</el-button>
            <el-button size="small" type="text"
              @click="$router.push(`/exterpriseDetail?id=${scope.row.id}`)">查看</el-button>

            <auth-btn btnPerm="park:enterprise:add_edit">
              <el-button size="small" type="text" @click="editRent(scope.row.id)">编辑</el-button>
            </auth-btn>

            <auth-btn btnPerm="park:enterprise:remove">
              <el-button size="small" type="text"
                @click="delExterprise(scope.row.id)">删除</el-button>
            </auth-btn>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container" style="float: right;">
      <el-pagination layout="total, prev, pager, next" :total="total" :page-size="params.pageSize"
        @current-change="pageChange" />
    </div>
    <!-- 添加合同对话框 -->
    <el-dialog draggable top="15vh" modal title="添加合同" v-model="rentDialogVisible" width="580px" @close="closeDialog">
      <!-- 表单区域 -->
      <!-- 表单模版 -->
      <div class="form-container">
        <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option v-for="item in buildList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker v-model="rentForm.rentTime" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload action="#" :http-request="uploadHandle" :before-upload="beforeUpload" :file-list="contractList"
              :limit="1" :on-exceed="onExceed">
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <div slot="tip" class="el-upload__tip">支持扩展名：.doc .pdf, 文件大小不超过5M</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="small" @click="closeDialog">取 消</el-button>
        <el-button size="small" type="primary" @click="onCommitRent">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}
 
.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>